package com.yousu.dashijixm.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.yousu.dashijixm.mapper.ArticleMapper;
import com.yousu.dashijixm.pojo.Article;
import com.yousu.dashijixm.pojo.PageBean;
import com.yousu.dashijixm.service.ArticleService;
import com.yousu.dashijixm.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * @Author: YouSu
 * @Version: 1.0
 * @CreateTime: 2023-11-23  14:28
 * 文章管理服务层
 */
@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    @Override //添加/发布文章
    public void add(Article article) {
        //补充属性值
        article.setCreateTime(LocalDateTime.now());
        article.setUpdateTime(LocalDateTime.now());
        //获取创建人信息
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        article.setCreateUser(id);
        //解决富文本带来的<P></P>问题
        String input = article.getContent();
        String output = input.replaceAll("<p>", "").replaceAll("</p>", "");
        article.setContent(output);
//        System.out.println(output);
        //调用数据层
        articleMapper.add(article);
    }

    @Override
    public void update(Article article) {
        article.setUpdateTime(LocalDateTime.now());
        //解决富文本带来的<P></P>问题
        String input = article.getContent();
        String output = input.replaceAll("<p>", "").replaceAll("</p>", "");
        article.setContent(output);

        articleMapper.update(article);
    }

    @Override
    public Article detail(Integer id) {
        Article article = articleMapper.detail(id);
        return article;
    }

    @Override
    public void delete(Integer id) {
        articleMapper.delete(id);
    }

    @Override //分页查询
    public PageBean<Article> list(Integer pageNum, Integer pageSize, Integer categoryId, String state) {
        //创建PageBean
        PageBean pageBean = new PageBean();

        //调用mybatis提供的插件PageHelper进行分页查询
        PageHelper.startPage(pageNum,pageSize);

        // 调用mapper层
        Map<String,Object>map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        List<Article> a = articleMapper.list(userId,categoryId,state);



        //进行强转为page,因为父类是调用不了子类的方法的
        Page<Article> page = (Page<Article>) a;

        //封装进PageBean
        pageBean.setTotal(page.getTotal());
        pageBean.setItems(page.getResult());
        return pageBean;

    }


}
